package easeui.ui;

import android.content.ClipboardManager;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v4.widget.SwipeRefreshLayout.OnRefreshListener;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.ListView;
import android.widget.Toast;

import com.github.postsanf.yinian.BaseApplication;
import com.github.postsanf.yinian.R;
import com.github.postsanf.yinian.bean.YNHistory;
import com.github.postsanf.yinian.constants.CommonConstants;
import com.github.postsanf.yinian.entity.YNHistoryMessageResponse;
import com.github.postsanf.yinian.utils.ReqUtils;
import com.github.postsanf.yinian.utils.StringUtils;
import com.google.gson.Gson;
import com.hyphenate.chat.EMClient;
import com.hyphenate.chat.EMConversation;
import com.litesuits.http.HttpConfig;
import com.litesuits.http.LiteHttp;
import com.litesuits.http.exception.HttpException;
import com.litesuits.http.listener.HttpListener;
import com.litesuits.http.request.StringRequest;
import com.litesuits.http.request.param.HttpMethods;
import com.litesuits.http.response.Response;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;

import easeui.EaseConstant;
import easeui.controller.EaseUI;
import easeui.utils.EaseCommonUtils;
import easeui.widget.EaseChatMessageHistoryList2;
import easeui.widget.EaseVoiceRecorderView;
import easeui.widget.chatrow.EaseCustomChatRowHistoryProvider2;

/**
 * you can new an EaseChatFragment to use or you can inherit it to expand.
 * You need call setArguments to pass chatType and userId
 * <br/>
 * <br/>
 * you can see ChatActivity in demo for your reference
 */
public class EaseChatHistoryFragment2 extends EaseBaseFragment {
    protected static final String TAG = "EaseChatFragment";
    protected static final int REQUEST_CODE_MAP = 1;
    protected static final int REQUEST_CODE_CAMERA = 2;
    protected static final int REQUEST_CODE_LOCAL = 3;

    /**
     * params to fragment
     */
    protected Bundle fragmentArgs;
    protected int chatType;
    protected String toChatUsername;
    protected EaseChatMessageHistoryList2 messageList;
    protected EMConversation conversation;

    protected InputMethodManager inputManager;
    protected ClipboardManager clipboard;
    protected Handler handler = new Handler();
    protected EaseVoiceRecorderView voiceRecorderView;
    protected SwipeRefreshLayout swipeRefreshLayout;
    protected ListView listView;

    protected boolean isloading;
    protected boolean haveMoreData = true;
    protected int pagesize = 20;

    private BaseApplication application;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        application = (BaseApplication) getActivity().getApplication();
        return inflater.inflate(R.layout.ease_fragment_chat_history2, container, false);
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        fragmentArgs = getArguments();
        // check if single chat or group chat
        chatType = fragmentArgs.getInt(EaseConstant.EXTRA_CHAT_TYPE, EaseConstant.CHATTYPE_SINGLE);
        // userId you are chat with or group id
        toChatUsername = fragmentArgs.getString(EaseConstant.EXTRA_USER_ID);
        super.onActivityCreated(savedInstanceState);
    }


    /**
     * init view
     */
    protected void initView() {
        // hold to record voice
        //noinspection ConstantConditions
        voiceRecorderView = (EaseVoiceRecorderView) getView().findViewById(R.id.voice_recorder);
        // message list layout
        messageList = (EaseChatMessageHistoryList2) getView().findViewById(R.id.message_list);
        if (chatType != EaseConstant.CHATTYPE_SINGLE)
            messageList.setShowUserNick(true);
        listView = messageList.getListView();
        swipeRefreshLayout = messageList.getSwipeRefreshLayout();
        swipeRefreshLayout.setColorSchemeResources(R.color.holo_blue_bright, R.color.holo_green_light,
                R.color.holo_orange_light, R.color.holo_red_light);

        inputManager = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
        clipboard = (ClipboardManager) getActivity().getSystemService(Context.CLIPBOARD_SERVICE);
        getActivity().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
    }

    protected void setUpView() {
        titleBar.setTitle("聊天记录");
        titleBar.setTitleColor(getResources().getColor(R.color.chat_title_color));
        titleBar.setBackgroundColor(getResources().getColor(R.color.bottom_text_color_normal));
        if (chatType != EaseConstant.CHATTYPE_CHATROOM) {
            onConversationInit();
            onMessageListInit();
        }
        titleBar.setLeftLayoutClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });
        setRefreshLayoutListener();
    }


    protected void onConversationInit() {
        conversation = EMClient.getInstance().chatManager().getConversation(toChatUsername, EaseCommonUtils.getConversationType(chatType), true);
        if (conversation == null)
            return;
        conversation.markAllMessagesAsRead();
    }

    protected void onMessageListInit() {
        messageList.init(toChatUsername, chatType, chatFragmentHelper != null ?
                chatFragmentHelper.onSetCustomChatRowProvider() : null);
        setListItemClickListener();
    }

    protected void setListItemClickListener() {
        messageList.setItemClickListener(new EaseChatMessageHistoryList2.MessageListItemClickListener() {

            @Override
            public void onUserAvatarClick(String username) {
                if (chatFragmentHelper != null) {
                    chatFragmentHelper.onAvatarClick(username);
                }
            }

            @Override
            public void onUserAvatarLongClick(String username) {
                if (chatFragmentHelper != null) {
                    chatFragmentHelper.onAvatarLongClick(username);
                }
            }

            @Override
            public void onResendClick(final YNHistory message) {
//                new EaseAlertDialog(getActivity(), R.string.resend, R.string.confirm_resend, null, new EaseAlertDialog.AlertDialogUser() {
//                    @Override
//                    public void onResult(boolean confirmed, Bundle bundle) {
//                        if (!confirmed) {
//                            return;
//                        }
//                        resendMessage(message);
//                    }
//                }, true).show();
            }

//            @Override
//            public void onBubbleLongClick(EMMessage message) {
//                contextMenuMessage = message;
//                if (chatFragmentHelper != null) {
//                    chatFragmentHelper.onMessageBubbleLongClick(message);
//                }
//            }

            @Override
            public boolean onBubbleClick(YNHistory message) {
                if (chatFragmentHelper == null) {
                    return false;
                }
                return chatFragmentHelper.onMessageBubbleClick(message);
            }

        });
    }

    protected void setRefreshLayoutListener() {
        swipeRefreshLayout.setOnRefreshListener(new OnRefreshListener() {

            @Override
            public void onRefresh() {
                new Handler().postDelayed(new Runnable() {

                    @Override
                    public void run() {
                        if (listView.getFirstVisiblePosition() == 0 && !isloading && haveMoreData) {
                            if (application.getEmHistoryList().get(0) == null)
                                return;
                            String chatid = application.getEmHistoryList().get(0).getChatID();
                            if (StringUtils.isEmpty(chatid))
                                return;
                            final List<YNHistory> messages = new ArrayList<YNHistory>();
                            LinkedHashMap<String, String> mParam = new LinkedHashMap<>();
                            mParam.put("gimid", toChatUsername);
                            mParam.put("type", "loading");
                            mParam.put("chatID", chatid);
                            StringRequest req = new StringRequest(getString(R.string.CHAT_HISTORY_MESSAGE))
                                    .setMethod(HttpMethods.Post)
                                    .setParamMap(mParam)
                                    .setHttpListener(new HttpListener<String>(true, false, true) {
                                        @Override
                                        public void onSuccess(String s, Response<String> response) {
                                            YNHistoryMessageResponse historyMessageResponse = new Gson().fromJson(s, YNHistoryMessageResponse.class);
                                            if (historyMessageResponse != null && ReqUtils.isSuccess(historyMessageResponse.getCode())) {
                                                List<YNHistory> data = historyMessageResponse.getData();
                                                messages.addAll(data);
                                                for (YNHistory ynHistory3 : application.getEmHistoryList()) {
                                                    messages.add(ynHistory3);
                                                }
                                                application.setEmHistoryList(null);
                                                application.setEmHistoryList(messages);
                                                if (data.size() > 0) {
                                                    messageList.refreshSeekTo(data.size() - 1);
                                                    if (data.size() != pagesize) {
                                                        haveMoreData = false;
                                                    }
                                                } else {
                                                    haveMoreData = false;
                                                }
                                                isloading = false;
                                            }
                                        }

                                        @Override
                                        public void onFailure(HttpException e, Response<String> response) {
                                            Toast.makeText(getActivity(), CommonConstants.YN_NET_LINK, Toast.LENGTH_SHORT).show();
                                        }
                                    });
                            LiteHttp.newApacheHttpClient(new HttpConfig(getActivity())).executeAsync(req);
                        } else {
                            Toast.makeText(getActivity(), getResources().getString(R.string.no_more_messages),
                                    Toast.LENGTH_SHORT).show();
                        }
                        swipeRefreshLayout.setRefreshing(false);
                    }
                }, 600);
            }
        });
    }


    @Override
    public void onResume() {
        super.onResume();
        EaseUI.getInstance().pushActivity(getActivity());
    }

    @Override
    public void onStop() {
        super.onStop();
        EaseUI.getInstance().popActivity(getActivity());
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    public void onBackPressed() {
        getActivity().finish();
    }

    protected EaseChatFragmentHelper chatFragmentHelper;

    public void setChatFragmentListener(EaseChatFragmentHelper chatFragmentHelper) {
        this.chatFragmentHelper = chatFragmentHelper;
    }

    public interface EaseChatFragmentHelper {
        /**
         * set message attribute
         */
        void onSetMessageAttributes(YNHistory message);

        /**
         * enter to chat detail
         */
        void onEnterToChatDetails();

        /**
         * on avatar clicked
         *
         * @param username
         */
        void onAvatarClick(String username);

        /**
         * on avatar long pressed
         *
         * @param username
         */
        void onAvatarLongClick(String username);

        /**
         * on message bubble clicked
         */
        boolean onMessageBubbleClick(YNHistory message);

        /**
         * on message bubble long pressed
         */
        void onMessageBubbleLongClick(YNHistory message);

        /**
         * on extend menu item clicked, return true if you want to override
         *
         * @param view
         * @param itemId
         * @return
         */
        boolean onExtendMenuItemClick(int itemId, View view);

        /**
         * on set custom chat row provider
         *
         * @return
         */
        EaseCustomChatRowHistoryProvider2 onSetCustomChatRowProvider();
    }

}
